package com.glory.brepda.activity.mfg;

import android.os.Handler;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.glory.brepda.R;
import com.glory.brepda.adapter.PublicAuditListAdapter;
import com.glory.brepda.base.BaseActivity;
import com.glory.brepda.callback.CustomDialogEntityCallBack;
import com.glory.brepda.entity.PackageDetailListEntity;
import com.glory.brepda.entity.response.BaseResponseBean;
import com.glory.brepda.utils.LotUtils;
import com.glory.brepda.utils.NetUtils;
import com.google.gson.JsonObject;
import com.google.gson.reflect.TypeToken;
import com.lzy.okgo.model.Response;
import com.pda.platform.ui.ui_pdaplatform.callback.FreeUI_EntityCallBack;
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_StaticMembers;
import com.pda.platform.ui.ui_pdaplatform.view.FreeUI_ClearEditText;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import androidx.recyclerview.widget.RecyclerView;
import butterknife.BindView;
import butterknife.OnClick;

public class InnerBoxCheckActivity extends BaseActivity {

    @BindView(R.id.tvTitle)
    TextView tvTitle;
    @BindView(R.id.tvBaseSubmit)
    TextView tvBaseSubmit;
    @BindView(R.id.etJobNo)
    FreeUI_ClearEditText etJobNo;
    @BindView(R.id.etLotID)
    FreeUI_ClearEditText etLotID;
    @BindView(R.id.etInnerBoxID)
    FreeUI_ClearEditText etInnerBoxID;
    @BindView(R.id.etLvBoDaiID)
    FreeUI_ClearEditText etLvBoDaiID;
    @BindView(R.id.tvAdd)
    TextView tvAdd;
    @BindView(R.id.rvLvBoDaiList)
    RecyclerView rvLvBoDaiList;
    @BindView(R.id.llMain)
    LinearLayout llMain;
    @BindView(R.id.tvQty)
    TextView tvQty;
    @BindView(R.id.tvPackMainQty)
    TextView tvPackMainQty;
    @BindView(R.id.tvMainQty)
    TextView tvMainQty;
    @BindView(R.id.tvBoxQty)
    TextView tvBoxQty;
    @BindView(R.id.tvDaiQty)
    TextView tvDaiQty;
    private boolean isLvBoDaiID = true;
    private PublicAuditListAdapter mPublicAuditListAdapter;
    private int mainQty = 0;
    private int packMainQty = 0;
    private PackageDetailListEntity body;
    private boolean isSubmit = true;
    List<String> minPackageType = Arrays.asList("LBL", "REEL", "LBD","DAI");

    @Override
    protected int getLayoutResId() {
        return R.layout.activity_inner_box_check;
    }

    @Override
    protected void initView() {
        String title = getIntent().getStringExtra(FreeApi_StaticMembers.SHOW_PLUGIN_KEY);
        tvTitle.setText(title);
        setMainLayout(llMain);
        tvBaseSubmit.setVisibility(View.GONE);
        initRecyclerView(rvLvBoDaiList, this);
        mPublicAuditListAdapter = new PublicAuditListAdapter(null, false,"");
        mPublicAuditListAdapter.openLoadAnimation(BaseQuickAdapter.ALPHAIN);
        mPublicAuditListAdapter.isFirstOnly(true);
        rvLvBoDaiList.setAdapter(mPublicAuditListAdapter);

        initEdit(etLotID,s ->{
            if (s.contains("/CLEANBOXID") || s.contains("/cleanBoxId")){
                etInnerBoxID.setText("");
                etLotID.setText(getText(etLotID).split("/")[0]);
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        etInnerBoxID.requestFocus();
                    }
                }, 500);
                return;
            }
        });

        initEdit(etInnerBoxID, s -> {
            if (s.contains("/CLEANBOXID") || s.contains("/cleanBoxId")){
                etInnerBoxID.setText("");
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        etInnerBoxID.requestFocus();
                    }
                }, 500);
                return;
            }
            FreeUI_EntityCallBack<BaseResponseBean<PackageDetailListEntity>> callBack = new CustomDialogEntityCallBack<BaseResponseBean<PackageDetailListEntity>>
                    (new TypeToken<BaseResponseBean<PackageDetailListEntity>>() {
                    }.getType(), getSupportFragmentManager(), this) {

                @Override
                public void onSuccess(Response<BaseResponseBean<PackageDetailListEntity>> response) {
                    super.onSuccess(response);
                    if (response.body().isSuccess(InnerBoxCheckActivity.this, false, getSupportFragmentManager())) {
                        PackageDetailListEntity body = response.body().getResponse().getBody();
                        if (!"BOX".equals(body.getXpackagedetail().getPackageType())) {
                            showToast("请输入正确的内盒ID", false);
                            etInnerBoxID.setText("");
                            etInnerBoxID.requestFocus();
                        }
                        etLvBoDaiID.requestFocus();
                    }
                }

                @Override
                public void onError(Response<BaseResponseBean<PackageDetailListEntity>> response) {
                    super.onError(response);

                }
            };
            JsonObject map = new JsonObject();
            map.addProperty("ACTION_TYPE", "QUERY");
            map.addProperty("CHECKPACKLOTID", s);
            map.addProperty("LOT_ID", getText(etLotID));
            NetUtils.requestPostNet("IF.LBLAPPROVE", "Common", InnerBoxCheckActivity.this, map, callBack);
        });
        initEdit(etLvBoDaiID, s -> {
            if (s.contains("/CLEANBOXID") || s.contains("/cleanBoxId")){
                etInnerBoxID.setText("");
                etLvBoDaiID.setText(getText(etLvBoDaiID).split("/")[0]);
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        etInnerBoxID.requestFocus();
                    }
                }, 500);
                return;
            }
            FreeUI_EntityCallBack<BaseResponseBean<PackageDetailListEntity>> callBack = new CustomDialogEntityCallBack<BaseResponseBean<PackageDetailListEntity>>
                    (new TypeToken<BaseResponseBean<PackageDetailListEntity>>() {
                    }.getType(), getSupportFragmentManager(), this) {

                @Override
                public void onSuccess(Response<BaseResponseBean<PackageDetailListEntity>> response) {
                    super.onSuccess(response);
                    if (response.body().isSuccess(InnerBoxCheckActivity.this, false, getSupportFragmentManager())) {
                        body = response.body().getResponse().getBody();
                        List<String> packageType = Arrays.asList("LBL", "REEL", "LBD","DAI");
                        if (packageType.contains(body.getXpackagedetail().getPackageType())) {
                            if (getText(etInnerBoxID).equals("")){
                                showToast("请输入内盒ID", false);
                            }else {
                                if (packageType.contains(body.getXpackagedetail().getPackageType())){
                                    mainQty += body.getXpackagedetail().getPackMainQty();
                                    packMainQty = body.getXpackagedetail().getPackMainQty();
                                    tvPackMainQty.setText(body.getXpackagedetail().getPackMainQty()+"");
                                    tvMainQty.setText(mainQty+"");
                                }
                                publicAudit("APPROVE", getText(etLotID), getText(etInnerBoxID), getText(etLvBoDaiID));
                            }
                        } else {
                            showToast("请输入正确的铝箔袋ID", false);
                            etLvBoDaiID.setText("");
                            etLvBoDaiID.requestFocus();
                        }
                    }
                }

                @Override
                public void onError(Response<BaseResponseBean<PackageDetailListEntity>> response) {
                    super.onError(response);

                }
            };
            JsonObject map = new JsonObject();
            map.addProperty("ACTION_TYPE", "QUERY");
            map.addProperty("CHECKPACKLOTID", s);
            map.addProperty("LOT_ID", getText(etLotID));
            NetUtils.requestPostNet("IF.LBLAPPROVE", "Common", InnerBoxCheckActivity.this, map, callBack);

        });
    }

    private void publicAudit(String ACTION_TYPE, String lotID, String packLotID, String packlotid) {
        FreeUI_EntityCallBack<BaseResponseBean<PackageDetailListEntity>> callBack = new CustomDialogEntityCallBack<BaseResponseBean<PackageDetailListEntity>>
                (new TypeToken<BaseResponseBean<PackageDetailListEntity>>() {
                }.getType(), getSupportFragmentManager(), this) {

            @Override
            public void onSuccess(Response<BaseResponseBean<PackageDetailListEntity>> response) {
                super.onSuccess(response);
                if (response.body().isSuccess(InnerBoxCheckActivity.this, false, getSupportFragmentManager())) {
                    PackageDetailListEntity body = response.body().getResponse().getBody();

                    for (PackageDetailListEntity s : mPublicAuditListAdapter.getData()) {
                        if (s.getPACKLOTID().equals(etLvBoDaiID.getText().toString())) {
                            showToast("当前包装条码已在列表中", false);
                            isLvBoDaiID = false;
                            break;
                        }
                    }
                    PackageDetailListEntity packageDetailListEntity =
                            new PackageDetailListEntity(etInnerBoxID.getText().toString(), etLvBoDaiID.getText().toString());
                    if (isLvBoDaiID) {
                        mPublicAuditListAdapter.addData(packageDetailListEntity);
                        etLvBoDaiID.setText("");
                        etLvBoDaiID.requestFocus();
                        tvQty.setText(mPublicAuditListAdapter.getData().size()+"");

                    } else {
                        isLvBoDaiID = true;
                        etLvBoDaiID.setText("");
                        etLvBoDaiID.requestFocus();
                    }
                    ArrayList<String> daiList = new ArrayList<>();
                    ArrayList<String> boxList = new ArrayList<>();
                    for (PackageDetailListEntity data:mPublicAuditListAdapter.getData()) {
                        if (!daiList.contains(data.getPACKLOTID())){
                            daiList.add(data.getPACKLOTID());
                        }
                        if (!boxList.contains(data.getWOID())){
                            boxList.add(data.getWOID());
                        }
                    }
                    tvBoxQty.setText(boxList.size()+"");
                    tvDaiQty.setText(daiList.size()+"");
                }else {
                    if (minPackageType.contains(body.getXpackagedetail().getPackageType())){
                        mainQty = mainQty - packMainQty;
                        tvMainQty.setText(mainQty+"");
                    }
                }
            }

            @Override
            public void onError(Response<BaseResponseBean<PackageDetailListEntity>> response) {
                super.onError(response);

            }
        };
        JsonObject map = new JsonObject();
        // L210300005
        // 2109_0000032
        map.addProperty("ACTION_TYPE", ACTION_TYPE);
//        map.addProperty("ACTION_TYPE", "QUERY");
        if (!ACTION_TYPE.equals("QUERY")) {
            map.addProperty("PARENTPACKLOTID", packLotID);
            map.addProperty("LOT_ID", lotID);
            map.addProperty("CHECKTYPE", "boxCheck");
        }
        map.addProperty("CHECKPACKLOTID", packlotid);
        NetUtils.requestPostNet("IF.LBLAPPROVE", "Common", InnerBoxCheckActivity.this, map, callBack);

    }

    @Override
    protected void initData() {

    }

    @OnClick({R.id.tvBaseSubmit})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tvBaseSubmit:
//                if (actionControl("Submit09"))return;
                if (mPublicAuditListAdapter.getData().size() <= 0) {
                    showToast("请先添加核对信息", false);
                    return;
                }

                LotUtils.publicAudit(this, getSupportFragmentManager(), "BOX", "BOX", mPublicAuditListAdapter.getData());
                break;
//            case R.id.tvAdd:
//                if (getText(etLotID).equals("") || getText(etInnerBoxID).equals("")){
//                    showToast("批次号或外箱ID不能为空",false);
//                    return;
//                }
//
//                LotUtils.publicAudit(this, getSupportFragmentManager(), getText(etLotID), getText(etInnerBoxID), "BOX", new LotUtils.netCallback<PackageDetailListEntity>() {
//                    @Override
//                    public void onSuccess(PackageDetailListEntity response) {
//                        if (isHavePackID(response)){
//                            mPublicAuditListAdapter.addData(response);
//                            etLotID.setText("");
//                            etInnerBoxID.setText("");
//                        }
//                    }
//
//                    @Override
//                    public void onFail(Throwable t) {
//                        loadError(t,"PUBLICAUDIT");
//                    }
//                });
//                break;
        }

    }

    private boolean isHavePackID(PackageDetailListEntity response) {
        if (mPublicAuditListAdapter.getData().size() <= 0) {
            return true;
        }

        for (PackageDetailListEntity entity : mPublicAuditListAdapter.getData()) {
            if (entity.getPACKLOTID().equals(response.getPACKLOTID())) {
                showToast("当前包装条码已在列表中", true);
                return false;
            }
        }

        return true;
    }


}
